package org.swan.web.namespace.service.impl;

import org.springframework.stereotype.Service;
import org.stream.tool.db.ADOConnection;
import org.swan.web.exception.BusinessCode;
import org.swan.web.exception.BusinessException;
import org.swan.web.namespace.bean.NamespaceBean;
import org.swan.web.namespace.mapper.NamespaceMapper;
import org.swan.web.namespace.service.NamespaceService;
import java.util.List;
import java.util.Optional;

@Service
public class NamespaceServiceImpl implements NamespaceService {

    public NamespaceServiceImpl() {
    }

    @Override
    public Optional<NamespaceBean> getNamespaceById(long id) {
        if (id == -1L)
            return Optional.of(NamespaceBean.SAMPLE);
        return ADOConnection.runTask(factory -> factory.getMapper(NamespaceMapper.class).getById(id), Optional.class);
    }

    @Override
    public long addNamespace(NamespaceBean namespaceBean) {
        long result = ADOConnection.runTask(factory -> factory.getMapper(NamespaceMapper.class).add(namespaceBean), Long.class);
        return result;
    }

    @Override
    public NamespaceBean updateNamespace(NamespaceBean namespaceBean) {
        getNamespaceById(namespaceBean.getNamespaceId()).orElseThrow(() -> new BusinessException(BusinessCode.NAMESPACE_DO_NOT_EXIST, namespaceBean.getNamespaceId()));
        ADOConnection.runTask(factory -> factory.getMapper(NamespaceMapper.class).updateById(namespaceBean), Long.class);
        return getNamespaceById(namespaceBean.getNamespaceId()).get();
    }

    @Override
    public NamespaceBean deleteNamespaceById(long namespaceId) {
        NamespaceBean namespaceBean = getNamespaceById(namespaceId).orElseThrow(() -> new BusinessException(BusinessCode.NAMESPACE_DO_NOT_EXIST, namespaceId));
        ADOConnection.runTask(factory -> factory.getMapper(NamespaceMapper.class).deleteById(namespaceId), Long.class);
        return namespaceBean;
    }

    @Override
    public List<NamespaceBean> list(int offset, int rows) {
        return ADOConnection.runTask(factory -> factory.getMapper(NamespaceMapper.class).list(offset, rows), List.class);
    }
}
